<template>
  <!-- 群组管理 -->
  <div class="contentpad">
    <div v-if="particularsShow">
      <el-table
        style="width: 99%; font-size: 14px; margin-left: 1%"
        border
        responsive
        :height="tableHeight"
        :header-cell-style="{
          'text-align': 'left',
          color: '#000',
          'border-color': '#ccffff',
          background: '#ccffff',
        }"
        :cell-style="{ 'text-align': 'left', 'border-color': '#fff' }"
        :data="filteredData"
        @selection-change="handleSelectionChange"
        ref="table"
        @row-click="tz"
      >
        <el-table-column label="序号" width="120">
          <template scope="scope">
            <span v-show="scope.$index + 1 < 10">00{{ scope.$index + 1 }}</span>
            <span v-show="scope.$index + 1 > 9 && scope.$index + 1 < 100"
              >0{{ scope.$index + 1 }}</span
            >
            <span v-show="scope.$index + 1 > 99">{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="群组名称">
          <template slot-scope="scope">
            <span v-show="show">{{ scope.row.group_name || "--" }}</span>
            <el-input
              style="width: 200px"
              @change="changeGroupName(scope.row)"
              v-show="!show"
              v-model="scope.row.group_name"
            ></el-input>
          </template>
        </el-table-column>

        <el-table-column>
          <template slot="header">
            群组类型
            <!-- 点击搜索框7 -->
            <el-popover placement="bottom" trigger="click">
              <SceneTypeinput @filterscene="filtersceneTable" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>
          <template slot-scope="scope">
            <span v-show="show">{{ scope.row.group_type_name || "--" }}</span>

            <el-select
              :disabled="scope.row.group_devices.length > 0"
              @change="handleSelectionChange2"
              v-show="!show"
              v-model="scope.row.group_type_name"
            >
              <template v-for="item in groupTypeOptions">
                <el-option
                  :key="item.group_type"
                  :label="item.group_type_name"
                  :value="item.group_type_name"
                >
                </el-option
              ></template>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column>
          <template slot="header">
            所在空间
            <!-- 点击搜索框6 -->
            <el-popover placement="bottom" trigger="click">
              <LocationSpaceinput @filterspace="filterspaceTable" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>

          <template slot-scope="scope">
            <!-- <span v-show="show">{{ options.name || "--" }}</span> -->
            <el-select
              class="interspace"
              disabled
              v-show="show"
              style="width: 100%"
              v-model="scope.row.group_area_id"
              filterable
              placeholder="--"
            >
              <el-option
                v-for="item in options"
                :key="item.area_id"
                :label="item.name"
                :value="item.area_id"
              >
              </el-option>
            </el-select>
            <el-select
              v-show="!show"
              style="width: 100%"
              v-model="scope.row.group_area_id"
              filterable
              placeholder="请选择"
              @change="changeGroupArea(scope.row)"
            >
              <el-option
                v-for="item in options"
                :key="item.area_id"
                :label="item.name"
                :value="item.area_id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column>
          <template slot="header">
            设备数量
            <!-- 点击搜索框6  slot="reference" -->
            <el-popover placement="bottom" trigger="click">
              <LocationSpaceinput />
              <i class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>
          <template scope="scope">{{
            scope.row.group_devices.length
          }}</template>
        </el-table-column>
        <el-table-column width="100">
          <template slot="header">
            <el-button type="primary" @click="editGroup()">{{
              showxq ? "编辑" : "保存"
            }}</el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              type="text"
              @change="cc"
              v-show="!showxq"
              @click.native.stop="cc"
              @click="tabCopy(scope.row)"
              >复制</el-button
            >
            <el-button
              @change="cc"
              @click.native.stop="cc"
              type="text"
              @click="tabParticulars(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
        <!-- 复选框 -->
        <el-table-column v-if="!showxq" type="selection" width="60">
          <template slot="header"> </template>
        </el-table-column>
      </el-table>
      <div class="bottom-left">
        <el-button v-show="!show">取消保存</el-button>
      </div>
      <div class="bottom-right">
        <el-button @click="deleteDevice" v-show="!showxq">删除群组</el-button>
        <el-button
          @click="createGroup"
          :disabled="show === false ? true : false"
          :type="show === false ? 'info' : 'primary'"
          >创建群组</el-button
        >
      </div>
    </div>
    <!-- 详情界面 -->
    <div v-show="!particularsShow && !addequipment">
      <div class="table-TopMax">
        <div class="table-TOP">
          <span>群组设备</span>
          <el-divider direction="vertical"></el-divider>
          <div class="table-TOPcenter">
            <span>群组名称</span>
            <span>{{ csname }}</span>
          </div>
          <div class="table-TOPcenter">
            <span>群组类型</span>
            <span>{{ groupTypeName }}</span>
          </div>
          <div class="table-TOPcenter">
            <span>所属空间</span>
            <span>{{ groupAreaId }}</span>
          </div>
          <div class="table-TOPcenter">
            <span>设备数</span>
            <span>{{ sss.length }}</span>
          </div>
        </div>
        <div class="fanhui" @click="fanhui()">
          <i class="el-icon-back">返回</i>
        </div>
      </div>
      <el-table
        :data="filteredData1"
        v-loading="loading"
        border
        style="width: 98%; font-size: 14px; margin-left: 20px"
        :height="tableHeight"
        :header-cell-style="{
          'text-align': 'left',
          color: '#000',
          'border-color': '#ccffff',
          background: '#CCFFFF',
        }"
        :cell-style="{
          width: '100%',
          'text-align': 'left',
          'border-color': '#fff',
        }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" width="80">
          <template scope="scope">
            <span v-show="scope.$index + 1 < 10">00{{ scope.$index + 1 }}</span>
            <span v-show="scope.$index + 1 > 9 && scope.$index + 1 < 100"
              >0{{ scope.$index + 1 }}</span
            >
            <span v-show="scope.$index + 1 > 99">{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="dev_id">
          <template slot="header">
            MAC1<!-- 点击搜索框1 -->
            <el-popover placement="bottom" trigger="click">
              <MACinput @filtermac="filtermacTable" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>

          <template slot-scope="scope">
            <!-- 点颜色 -->
            <span
              style="font-size: 25px"
              :style="scope.row.online === 0 ? 'color:#aaa' : 'color:#0d0'"
              >●</span
            >
            <span style="margin-left: 10px">{{ scope.row.dev_id }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="dev_type_name">
          <template slot="header">
            设备类型
            <!-- 点击搜索框2 -->
            <el-popover placement="bottom" trigger="click">
              <FacilityTypeinput @filter="filterTable" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column prop="name">
          <template slot="header">
            设备名称
            <!-- 点击搜索框3 -->
            <el-popover placement="bottom" trigger="click">
              <FacilityNameinput @filtername="filternameTable" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>
          <template slot-scope="scope">
            <span align="center">{{ scope.row.name || "--" }} </span>
          </template>
        </el-table-column>

        <el-table-column prop="address">
          <template slot="header">
            所在空间
            <!-- 点击搜索框4 -->
            <el-popover placement="bottom" trigger="click">
              <LocationSpaceinput @filterspace="filterspaceTable1" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>
          <template slot-scope="scope">
            <el-select
              class="interspace"
              disabled
              v-show="show"
              style="width: 100%"
              v-model="scope.row.dev_ep_area_id"
              filterable
            >
              <el-option
                v-for="item in options"
                :key="item.area_id"
                :label="item.name"
                :value="item.area_id"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="dev_type">
          <template slot="header">
            图位编号
            <!-- 点击搜索框4 -->
            <el-popover placement="bottom" trigger="click">
              <MapNumberinput @filterposition="filterpositionTable" />
              <i slot="reference" class="el-icon-caret-bottom"></i>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column prop="address" label="操作" width="60">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="remove(scope.row)"
              >移除11</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="bottom-right">
        <el-button type="primary" @click="submit()">添加设备</el-button>
      </div>
    </div>
    <AddEquipment
      :message="currentDevList"
      :message1="currentGroup"
      v-if="addequipment"
      @back="addequipment = !addequipment"
      :fatherPage="sss"
    />
  </div>
</template>
<script>
import Api from "../../api/api";
import MACinput from "@/components/cominput/MACinput.vue";
import SceneTypeinput from "@/components/cominput/SceneTypeinput.vue";
import LocationSpaceinput from "@/components/cominput/LocationSpaceinput.vue";
import FacilityNameinput from "@/components/cominput/FacilityNameinput.vue";
import FacilityTypeinput from "@/components/cominput/FacilityTypeinput.vue";
import MapNumberinput from "@/components/cominput/MapNumberinput.vue";
import AddEquipment from "@/components/AddEquipment.vue";

export default {
  components: {
    SceneTypeinput,
    MACinput,
    LocationSpaceinput,
    FacilityTypeinput,
    FacilityNameinput,
    MapNumberinput,
    AddEquipment,
  },
  inject: ["reload"],
  data() {
    return {
      groupData: {
        groupName: "",
        groupType: "",
      },
      value1: "",
      sss: [],
      filteredData1: [],
      value2: "",
      csname: "",
      groupTypeName: "",
      groupAreaId: "",
      currentDevList: [],
      currentGroup: [],
      groupDevices: [],
      options: [],
      groupId: "",
      loading: true,
      addequipment: false,
      // localSid: localStorage.getItem("sid"),
      localSid: "577688740d9d258b92c61e6b1f5498ff",
      particularsShow: true,
      list: [],
      groupList: [],
      filteredData: [],
      multipleSelection: [],
      groupTypeOptions: [],
      show: true,
      showxq: true,
      iconkaiguan: true,
      state: "",
      tableHeight: window.innerHeight - 200,
    };
  },
  mounted() {},
  async created() {
    let res = await Api.query_areas({ params: { sid: this.localSid } });
    this.options = res.result.areas; //数据源二

    // const options = (this.options = res.result.areas);
    console.log("this.options>>", this.options);
    this.groupAreaId = this.options.area_id;

    //带有mac列数据的接口
    let res2 = await Api.exc({
      params: { sid: this.localSid },
    });

    let res3 = await Api.query_all_group_detail({
      params: { sid: this.localSid },
    });
    this.groupList = res3.result.group_list; //数据源一
    this.groupList[this.groupList.length - 1].group_devices = this.groupDevices;
    this.filteredData = JSON.parse(JSON.stringify(this.groupList));

    console.log("表格数据源>", this.groupList);
    console.log("的设备数量>", this.groupDevices);
    let groupType = await Api.get_group_type_info_list({
      params: { sid: this.localSid },
    });
    this.groupTypeOptions = groupType.result.group_type_info_list;
    console.log("this.groupTypeOptions>>>", this.groupTypeOptions);
    this.loading = false;

    // const groupList = group.concat(options); 数组合并

    function compare(property) {
      return function (a, b) {
        var value1 = a[property];
        var value2 = b[property];
        return value2 - value1;
      };
    }
    res2.result.device_ep_list.sort(compare("online"));
    this.list = res2.result.device_ep_list;
    console.log("this.list>>>", this.list);
    this.loading = false;
  },
  methods: {
    filtersceneTable(keywords) {
      if (keywords.trim() === "") {
        this.filteredData = JSON.parse(JSON.stringify(this.groupList));
      } else {
        this.filteredData = this.groupList.filter((row) => {
          return row.group_type_name.includes(keywords);
        });
      }
    },
    filterspaceTable(keywords) {
      // if (keywords.trim() === "") {
      //   this.filteredData = JSON.parse(JSON.stringify(this.groupList));
      // } else {
      //   this.filteredData = this.groupList.filter((row) => {
      console.log("所在空间", keywords);
      //     return row.group_area_id.includes(keywords);
      //   });
      // }
    },
    filterspaceTable1(keywords) {
      // if (keywords.trim() === "") {
      //   this.filteredData1 = JSON.parse(JSON.stringify(this.sss));
      // } else {
      //   this.filteredData1 = this.sss.filter((row) => {
      console.log("所在空间", keywords);
      //     return row.group_area_id.includes(keywords);
      //   });
      // }
    },
    filtermacTable(keywords) {
      if (keywords.trim() === "") {
        this.filteredData1 = JSON.parse(JSON.stringify(this.sss));
      } else {
        this.filteredData1 = this.sss.filter((row) => {
          return row.dev_id.includes(keywords);
        });
      }
    },
    filterTable(keywords) {
      if (keywords.trim() === "") {
        this.filteredData1 = JSON.parse(JSON.stringify(this.sss));
      } else {
        this.filteredData1 = this.sss.filter((row) => {
          return row.dev_type_name.includes(keywords);
        });
      }
    },
    filternameTable(keywords) {
      if (keywords.trim() === "") {
        this.filteredData1 = JSON.parse(JSON.stringify(this.sss));
      } else {
        this.filteredData1 = this.sss.filter((row) => {
          return row.name.includes(keywords);
        });
      }
    },
    filterpositionTable(keywords) {
      if (keywords.trim() === "") {
        this.filteredData1 = JSON.parse(JSON.stringify(this.sss));
      } else {
        this.filteredData1 = this.sss.filter((row) => {
          return row.dev_type.includes(keywords);
        });
      }
    },
    // 删除群组
    async deleteDevice() {
      const loading = this.$loading({
        lock: true,
        text: "加载中,请稍等片刻",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let idList = [];
      this.multipleSelection.forEach((el) => {
        idList.push(el.group_id);
      });
      await Api.delete_groups({
        params: { sid: this.localSid, group_id_list: idList },
      });
      loading.close();
      this.reload();
    },
    handleSelectionChange2(val) {
      console.log("val>>>>>>>>>>>>>>>>>>>>>>>>>>", val);
      this.multipleSelection2 = val;
    },
    tz(row, column, event) {
      console.log(row, column, event);
      this.$refs.table.toggleRowSelection(row);
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },

    handleSelectionChange(val) {
      console.log("val>>>>>>>>>>>>>>>>>", val);
      this.multipleSelection = val;
    },
    loadData() {
      // 模拟加载数据的过程
      this.particularsShow = !this.particularsShow;
      // 设置shouldShowContent的值
      this.particularsShow = this.someMethod() > 10;
    },
    someMethod() {
      // 这里是一些计算的逻辑，适当减少v-if中的计算量
      return Math.floor(Math.random() * 20);
    },
    // 群组名称修改
    async changeGroupName(row) {
      await Api.update_group({
        params: {
          sid: this.localSid,
          group_id: row.group_id,
          group_name: row.group_name,
        },
      });
      this.$message({
        showClose: true,
        message: "修改成功",
        type: "success",
      });
    },
    // 阻止冒泡事件（忽略）
    cc() {},
    // 创建群组
    async createGroup() {
      // 创建后定位到底部
      // this.$nextTick(() => {
      //   const tableRows = this.$refs.table.$el.querySelectorAll("tbody tr");
      //   if (tableRows && tableRows.length) {
      //     const lastRow = tableRows[tableRows.length + 1];
      //     lastRow.scrollIntoView({ behavior: "smooth" });
      //   }
      // });
      // const tableEl = this.$refs.table.$el.querySelector(
      //   ".el-table__body-wrapper"
      // );
      // tableEl.scrollTop = tableEl.scrollHeight;

      await Api.add_group({
        params: {
          sid: this.localSid,
          group_name: "默认名称",
          group_type_name: "不限制",
        },
      });
      this.reload();
      // this.groupList.push(this.groupList[2]);
      this.$message({
        showClose: true,
        type: "success",
        message: "创建成功",
      });
    },
    // 编辑群组
    editGroup() {
      this.show = !this.show;
      this.showxq = !this.showxq;
      if (this.showxq) {
        this.$message({
          showClose: true,
          message: "保存成功",
          type: "success",
        });
      }
    },
    // 所在空间修改
    async changeGroupArea(row) {
      console.log("所在空间的下拉row>>>", row);
      await Api.update_group({
        params: {
          sid: this.localSid,
          group_id: row.group_id,
          group_area_id: row.group_area_id,
        },
      });
      this.$message({
        showClose: true,
        message: "修改成功",
        type: "success",
      });
    },
    // 保存群组
    saveGroup() {
      this.show = true;
    },
    // 复制群组
    async tabCopy(row) {
      console.log("我是row》》", row);
      // 复制后页面定位到最底部

      // this.groupDevices = row.group_devices;
      // this.groupList[this.groupList.length - 1].group_devices =
      // this.groupDevices;

      console.log("下面的 设备数量", this.groupDevices);
      await Api.add_group({
        params: {
          sid: this.localSid,
          group_name: row.group_name,
          group_type: row.group_type,
          group_devices: row.group_devices,
          status: 0,
        },
      });
      this.$message({
        showClose: true,
        type: "success",
        message: "复制成功",
      });
      this.reload();
    },
    // 详情
    async tabParticulars(row) {
      this.currentGroup = row;
      console.log("详情页面的数据源》", row);
      this.particularsShow = !this.particularsShow;
      this.csname = row.group_name;
      this.groupTypeName = row.group_type_name;
      this.groupId = row.group_id;

      // this.csname = row.group_name;
      console.log("点击本行的数据>>>", row);
      console.log("this.csname名字》》", this.csname);
      // this.value = row;
      let res = await Api.query_all_execute_device_ep_detail_by_group_type({
        params: { sid: this.localSid, group_type: row.group_type },
      });

      this.currentDevList = res.result.device_ep_list;
      console.log("添加设备的数据源this.currentDevList>>", this.currentDevList);

      let res2 = await Api.query_all_group_detail({
        params: { sid: this.localSid },
      });
      console.log(res2);
      this.sss = row.group_devices;
      this.filteredData1 = JSON.parse(JSON.stringify(this.sss));
      console.log("点击详情里面的数据源>>>", this.sss);
    },
    // 返回
    fanhui() {
      this.particularsShow = !this.particularsShow;
    },
    // 移除
    async remove(row) {
      console.log("移除行的数据", row);
      await Api.delete_group_device_by_id({
        params: { sid: this.localSid, group_device_id: row.group_device_id },
      });
      this.$message({
        showClose: true,
        type: "success",
        message: "移除成功",
      });
      this.reload();
    },
    // 添加
    submit() {
      this.addequipment = !this.addequipment;
      // for (let item of this.tableData1) {
      //   this.list.push(item);
      // }
      // this.$message({
      //   showClose: true,
      //   type: "success",
      //   message: "添加成功",
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.contentpad {
  width: 100%;
  height: calc(100vh - 80px);

  .table-TopMax {
    width: 98%;
    height: 50px;
    display: flex;
    margin-left: 20px;
    justify-content: space-between;
    // border-bottom: 1px solid rgb(219, 217, 215);

    .fanhui {
      :hover {
        cursor: pointer;
      }
    }

    .table-TOP {
      width: 60%;
      display: flex;
      justify-content: space-between;

      .table-TOPcenter {
        width: 20%;
        display: flex;

        span {
          width: 50%;
        }

        span:nth-child(2) {
          text-align: left;
          color: rgb(219, 217, 215);
        }
      }
    }
  }
  // 列表的下拉样式
  .interspace {
    ::v-deep .el-input.is-disabled .el-input__icon {
      display: none;
    }
    ::v-deep .el-input.is-disabled .el-input__inner {
      padding: 0 0 0 0;
      color: #606266;
      border: #fff;
      cursor: pointer;
      background: #ffffff00;
    }
  }

  // 去除滚动条
  ::v-deep .el-table th.gutter {
    display: none;
    width: 0;
  }
  ::v-deep .el-table colgroup col[name="gutter"] {
    display: none;
    width: 0;
  }
  ::v-deep .el-table__body {
    width: 100% !important;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  ::v-deep .el-dialog__header {
    border-bottom: 2px solid rgb(219, 217, 215);
    text-align: left;
  }

  .bottom-left {
    position: fixed;
    left: 260px;
    bottom: 2%;
  }

  .bottom-right {
    position: fixed;
    bottom: 2%;
    right: 3%;
  }

  .el-form {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: center;
  }
}
</style>
